package thread;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *   ReentrantReadWriteLock实现了ReadWriteLock接口，ReentrantReadWriteLock里面提供了很多丰富的方法，不过最主要的有两个方法：readLock()和writeLock()用来获取读锁和写锁
 */
public class ReentrantReadWriteLockTest {
    ReentrantReadWriteLock rwl=new ReentrantReadWriteLock();
    public static void main(String[] args)  {
        final ReentrantReadWriteLockTest test = new ReentrantReadWriteLockTest();

        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();

        new Thread(){
            public void run() {
                test.get(Thread.currentThread());
            };
        }.start();

    }

    public void get(Thread thread) {       //这里放读锁
        rwl.readLock().lock();
        try {
            for(int i=0;i<3;i++){
                System.out.println(thread.getName()+"正在进行读操作");
            }
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(thread.getName()+"读操作完毕");
        } finally {             //这里释放锁
            rwl.readLock().unlock();
        }
    }
}

